/*
 * @Author: your name
 * @Date: 2021-06-03 20:20:28
 * @LastEditTime: 2021-06-04 10:20:06
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /xiangpan-admin/src/components/table/index.tsx
 */
import React, { useEffect } from 'react';
import { Table } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import { useRequest } from '@/.umi/plugin-request/request';
import useObj from '@/use/useObj';
import { AxiosResponse } from 'axios';
import { TablePaginationConfig } from 'antd';
import _ from '@umijs/deps/compiled/lodash';

interface IProps<T> {
  columns: ColumnsType<T>;
  request: (data: any) => Promise<AxiosResponse<any>>;
  query?: Object;
}

interface IObj {
  pagination: {
    page_num: number;
    page_size: number;
  };
  total: number;
  [type: string]: any;
}

const TableComponent = <T extends {}>(props: IProps<T>) => {
  const [obj, setObj] = useObj<IObj>({
    pagination: {
      page_num: 1,
      page_size: 10,
    },
    total: 0,
  });
  const { columns, query, request } = props;

  const { data, error, loading, refresh, run } = useRequest(
    () => request({ ...query, ...obj.pagination }),
    {
      refreshDeps: [obj.pagination, query],
    },
  );

  useEffect(() => {
    if (data?.results[0].total) {
      console.log(data.results[0].total, 'data.results[0].total=');

      setObj({ total: data.results[0].total || 0 });
    }
  }, [data]);

  console.log(data, 'useRequest===data---');
  return (
    <Table
      rowKey={(record, index) => {
        return Math.random();
      }}
      loading={loading}
      columns={columns}
      dataSource={data?.results}
      pagination={{
        current: obj.pagination.page_num,
        pageSize: obj.pagination.page_size,
        total: obj.total,
      }}
      onChange={(pagination: TablePaginationConfig): void => {
        const { current, pageSize } = pagination;
        setObj((obj: IObj) => {
          obj.pagination.page_num = current || 1;
          obj.pagination.page_size = pageSize || 10;
        });
      }}
    />
  );
};
export default TableComponent;
